package MicroTime;

import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtil {
    public static Connection getPhoenixConnection(String phoenixUrl) throws ClassNotFoundException, SQLException {
        String phoenixDriver = Constants.PHOENIX_DRIVER;
        return getJdbcConnection(phoenixDriver, phoenixUrl);
    }

    public static Connection getJdbcConnection(String driver, String url) throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        return DriverManager.getConnection(url);
    }
    
    public static <T> List<T> queryList(Connection conn,
                                        String sql,
                                        Object[] args,
                                        Class<T> tClass) {
        List<T> result = new ArrayList<>();
        // ?,?,?
        
        //查询数据库
        try {
            PreparedStatement ps = conn.prepareStatement(sql);


            // 给sql中的占位符进行赋值
            for (int i = 0; args != null && i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            
            ResultSet resultSet = ps.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            
            // 1   lisi     new T
            // 2   zs       new T
            while (resultSet.next()) {
                //创建一个T类型的对象, 把每列的数据都封装到T对象中
                T t = tClass.newInstance();  //通过反射的方式创建泛型对象.
                for (int i = 1; i <= metaData.getColumnCount(); i++) {  // 遍历每列数据
                    String columnName = metaData.getColumnName(i);
                    Object value = resultSet.getObject(columnName);
                    BeanUtils.setProperty(t, columnName, value);
                }

                result.add(t);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }
}